﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
using Uiap.Infrastructure.SeedWork;

namespace Uiap.Infrastructure.RunTime.Mvc
{
    public class ModelValidationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var response = new AjaxResponse();
            //模型参数验证不通过
            if (!context.ModelState.IsValid)
            {
                var errors = new StringBuilder();
                foreach (var key in context.ModelState.Keys)
                {
                    foreach (var error in context.ModelState[key].Errors)
                    {
                        if (error.Exception == null)
                        {
                            errors.AppendFormat("{0},", error.ErrorMessage);
                        }
                        else
                        {
                            errors.AppendFormat("{0}-{1},", key, error.Exception.InnerException != null
                                ? error.Exception.InnerException.Message
                                : error.Exception.Message);
                        }
                    }
                }
                response.Success = false;
                response.Error = new ErrorInfo() { Message = string.Format("参数验证错误：{0}", errors.ToString().TrimEnd(',')) };

                context.Result = new JsonResult(response);
            }
            base.OnActionExecuting(context);
        }
    }
}
